<template>
	<a-form :ref="'ruleForm'" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
		<a-collapse ghost v-model:activeKey="activeKey">
			<a-collapse-panel key="1" header="数值配置">
				<a-row :gutter="[10, 10]">
					<a-col :span="24">
						<a-radio-group
							v-model:value="formState.dataSetConfig.dataSetType"
							optionType="button"
							buttonStyle="solid"
							:options="[
								{ label: '静态', value: 0 },
								{ label: '数据源', value: 1 }
							]"
						>
						</a-radio-group>
					</a-col>

					<a-col :span="24" v-if="formState.dataSetConfig.dataSetType == 0">
						<JsonEditor v-model="formState.data" />
					</a-col>
					<template v-else>
						<a-col :span="24">
							<SelectTree @onChange="selectTreeChange" v-model:paramsJson="formState.dataSetConfig.dataSetJson" />
						</a-col>
						<a-col :span="24">
							<div class="custom-select-container">
								<a-select
									v-if="!formState.dataSetConfig.dataSetFields || formState.dataSetConfig.dataSetFields.length === 0"
									style="width: 100%"
									placeholder="请选择展示字段"
									mode="tags"
									v-model:value="tempSelectedFields"
									@change="selectDataSet"
									optionLabelProp="label"
								>
									<a-select-option
										v-for="optionItem in dataOption"
										:value="optionItem"
										:key="optionItem"
										:label="optionItem"
									>
										{{ optionItem }}
									</a-select-option>
								</a-select>
								<template v-else>
									<div class="field-selection-area">
										<div class="field-container">
											<div class="field-header">
												<span>字段列表</span>
											</div>
											<div class="field-list">
												<div
													v-for="optionItem in filteredOptions"
													:key="optionItem"
													class="field-item selectable"
													@click="addField(optionItem)"
												>
													<span class="item-text">{{ optionItem }}</span>
													<span class="add-icon">
														<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
															<path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"></path>
														</svg>
													</span>
												</div>
											</div>
										</div>

										<div class="field-container">
											<div class="field-header">
												<span>已选字段（可拖拽排序）</span>
											</div>
											<VueDraggable
												v-model="formState.dataSetConfig.dataSetFields"
												item-key="field"
												handle=".drag-handle"
												@end="onDragEnd"
												class="field-list"
											>
												<template #item="{ element }">
													<div class="field-item">
														<div class="drag-handle">
															<svg viewBox="0 0 20 20" width="12" height="12" fill="currentColor">
																<path
																	d="M7 2a2 2 0 1 0 .001 4.001A2 2 0 0 0 7 2zm0 6a2 2 0 1 0 .001 4.001A2 2 0 0 0 7 8zm0 6a2 2 0 1 0 .001 4.001A2 2 0 0 0 7 14zm6-8a2 2 0 1 0-.001-4.001A2 2 0 0 0 13 6zm0 2a2 2 0 1 0 .001 4.001A2 2 0 0 0 13 8zm0 6a2 2 0 1 0 .001 4.001A2 2 0 0 0 13 14z"
																></path>
															</svg>
														</div>
														<div class="field-content">
															<div class="field-names">
																<div class="field-original">{{ element.field }}</div>
																<div class="field-alias" v-if="element.alias">别名: {{ element.alias }}</div>
															</div>
															<div class="field-actions">
																<a-button type="link" class="edit-btn" @click="editFieldAlias(element)">
																	<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
																		<path
																			d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
																		></path>
																	</svg>
																</a-button>
																<a-button type="link" class="delete-btn" @click="removeField(element)">
																	<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
																		<path
																			d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
																		></path>
																	</svg>
																</a-button>
															</div>
														</div>
													</div>
												</template>
												<template #footer v-if="formState.dataSetConfig.dataSetFields.length === 0">
													<div class="empty-placeholder">暂无已选字段，请从左侧列表选择</div>
												</template>
											</VueDraggable>
										</div>
									</div>
								</template>
							</div>
						</a-col>
					</template>
				</a-row>
			</a-collapse-panel>
		</a-collapse>
	</a-form>

	<!-- 别名编辑弹窗 -->
	<a-modal
		v-model:open="aliasModalVisible"
		title="编辑字段别名"
		@ok="saveFieldAlias"
		@cancel="aliasModalVisible = false"
		:okButtonProps="{ disabled: !currentAliasValue.trim() }"
	>
		<a-form layout="vertical">
			<a-form-item label="字段名">
				<a-input disabled :value="currentEditField.field" />
			</a-form-item>
			<a-form-item label="显示别名">
				<a-input v-model:value="currentAliasValue" placeholder="请输入字段别名" />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup>
	import { ref, computed, watch } from 'vue'
	import JsonEditor from '@/views/plugin/dashboard/plugin/public/JsonEditor/JsonEditor.vue'
	import SelectTree from '@/views/plugin/dashboard/plugin/public/SelectTree/SelectTree.vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import { designStore } from '@/views/plugin/dashboard/store'
	import VueDraggable from 'vuedraggable-es'
	const useDesignStore = designStore()
	// -----------------------------------------------------------
	import config from '../config'
	import { reactive, defineProps, defineEmits } from 'vue'
	const emits = defineEmits(['upDataConfig'])
	const props = defineProps({
		config: {
			type: Object,
			default: () => {
				return { ...config.data }
			}
		}
	})
	const activeKey = ref(['1'])
	// 数据源
	const dataSource = ref([])
	// 模拟接口返回下拉数据
	const dataOption = ref([])
	// 临时保存tags模式选中的值
	const tempSelectedFields = ref([])
	// 别名编辑弹窗
	const aliasModalVisible = ref(false)
	const currentEditField = ref({})
	const currentAliasValue = ref('')

	// 初始化表单状态
	const formState = reactive({
		data: props.config.data,
		dataSetConfig: {
			...props.config.dataSetConfig
		}
	})

	// 确保dataSetFields存在
	if (!formState.dataSetConfig.dataSetFields) {
		// 如果有旧数据，将其转换为新格式
		if (formState.dataSetConfig.dataSetId && formState.dataSetConfig.dataSetId.length > 0) {
			formState.dataSetConfig.dataSetFields = formState.dataSetConfig.dataSetId.map((field) => ({
				field,
				alias: ''
			}))
		} else {
			formState.dataSetConfig.dataSetFields = []
		}
	}

	// 保持向后兼容，同步到dataSetId
	watch(
		() => formState.dataSetConfig.dataSetFields,
		(newFields) => {
			formState.dataSetConfig.dataSetId = newFields.map((item) => item.field)
		},
		{ deep: true }
	)

	// 计算未选择的选项
	const filteredOptions = computed(() => {
		const selectedFieldNames = formState.dataSetConfig.dataSetFields.map((item) => item.field)
		return dataOption.value.filter((item) => !selectedFieldNames.includes(item))
	})

	// 添加字段
	const addField = (field) => {
		const fieldsArray = formState.dataSetConfig.dataSetFields
		if (!fieldsArray.some((item) => item.field === field)) {
			fieldsArray.push({
				field,
				alias: ''
			})
		}
	}

	// 移除字段
	const removeField = (fieldObj) => {
		const index = formState.dataSetConfig.dataSetFields.findIndex((item) => item.field === fieldObj.field)
		if (index !== -1) {
			formState.dataSetConfig.dataSetFields.splice(index, 1)
		}
	}

	// 编辑字段别名
	const editFieldAlias = (fieldObj) => {
		currentEditField.value = fieldObj
		currentAliasValue.value = fieldObj.alias || ''
		aliasModalVisible.value = true
	}

	// 保存字段别名
	const saveFieldAlias = () => {
		const index = formState.dataSetConfig.dataSetFields.findIndex((item) => item.field === currentEditField.value.field)
		if (index !== -1) {
			formState.dataSetConfig.dataSetFields[index].alias = currentAliasValue.value.trim()
		}
		aliasModalVisible.value = false
	}

	// 拖拽结束事件
	const onDragEnd = () => {
		// 可以在这里添加额外的处理逻辑
		console.log('拖拽排序完成', formState.dataSetConfig.dataSetFields)
	}

	// 获取下拉数据
	watch(
		() => formState.dataSetConfig.dataSetJson,
		(newVal) => {
			if (props.config.dataSetConfig.dataSetType === 1 && newVal) {
				const list = useDesignStore.dataSource || []
				let datasetId = ''
				let indicatorId = ''
				list.forEach((parent) => {
					parent.config.indicators.forEach((child) => {
						if (child.id === newVal.id) {
							datasetId = parent.id
							indicatorId = child.id
						}
					})
				})
				// 下拉数据
				if (datasetId && indicatorId) {
					datasetApi.querySelectedColumns({ datasetId, indicatorId }).then((res) => {
						dataOption.value = res || []
					})
					datasetApi.preview(newVal).then((res) => {
						dataSource.value = res || []
						formState.data.listValue.value = res || []
					})
				}
			}
		},
		{
			immediate: true,
			deep: true
		}
	)

	// 选择数据 (处理a-select的tags模式)
	const selectDataSet = (val) => {
		// 将新选择的标签转换为字段对象格式
		formState.dataSetConfig.dataSetFields = val.map((field) => ({
			field,
			alias: ''
		}))
		tempSelectedFields.value = [] // 清空临时数据
	}

	// 更新组件内容
	watch(
		() => formState,
		(newVal) => {
			emits('upDataConfig', { ...props.config, ...newVal })
		},
		{
			deep: true
		}
	)
</script>
<style scoped>
	:deep(.ant-radio-button-wrapper) {
		padding: 0;
		width: 100%;
	}

	:deep(.ant-radio-group) {
		display: flex;
		text-align: center;
	}

	.custom-select-container {
		width: 100%;
	}

	.field-selection-area {
		display: flex;
		gap: 12px;
		margin-top: 12px;
	}

	.field-container {
		flex: 1;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		height: 300px;
	}

	.field-header {
		padding: 8px;
		background-color: #f5f5f5;
		font-weight: 500;
		border-bottom: 1px solid #d9d9d9;
	}

	.field-list {
		overflow-y: auto;
		flex: 1;
		padding: 4px;
	}

	.field-item {
		display: flex;
		align-items: center;
		padding: 8px;
		margin-bottom: 4px;
		background-color: #f5f5f5;
		border-radius: 2px;
	}

	.field-item.selectable {
		cursor: pointer;
		align-items: center;
	}

	.field-item.selectable:hover {
		background-color: #e6f7ff;
	}

	.drag-handle {
		cursor: move;
		color: #999;
		margin-right: 8px;
		display: flex;
		align-items: center;
		padding-top: 2px;
	}

	.field-content {
		display: flex;
		flex: 1;
		justify-content: space-between;
		align-items: center;
	}

	.field-names {
		flex: 1;
		overflow: hidden;
	}

	.field-original {
		font-weight: 500;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.field-alias {
		font-size: 12px;
		color: #666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.field-actions {
		display: flex;
		align-items: center;
	}

	.item-text {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.add-icon {
		color: #1677ff;
	}

	.edit-btn {
		padding: 0;
		color: #1677ff;
		margin-right: 4px;
	}

	.edit-btn:hover {
		color: #40a9ff;
	}

	.delete-btn {
		padding: 0;
		color: #ff4d4f;
	}

	.delete-btn:hover {
		color: #ff7875;
	}

	.empty-placeholder {
		color: #999;
		text-align: center;
		padding: 16px 0;
	}
</style>
